import { UserService } from './../user/user.service';
import { ConflictException, Inject, Injectable, UnauthorizedException, UseGuards } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { verify } from 'argon2';
import { JwtPayload } from 'src/types/auth-jwtpayload';
import { JwtService } from '@nestjs/jwt';
import refreshConfig from 'config/refresh.config';
import { ConfigType } from '@nestjs/config';

@Injectable()
export class AuthService {
  constructor(private userService: UserService, private readonly jwtService: JwtService,    
  @Inject(refreshConfig.KEY)
  private refreshTokenConfig: ConfigType<typeof refreshConfig>,) {

  }
  async registerUser(createUserDto: CreateUserDto) {
    if (!createUserDto?.email) {
      throw new ConflictException('邮箱不能为空');
    }
    const user = await this.userService.findByEmail(createUserDto.email);
    if (user) throw new ConflictException('用户已经存在');
    return this.userService.create(createUserDto);
  }

  async validateLocalUser(email: string, password: string) {
    const user = await this.userService.findByEmail(email);
    if (!user) throw new ConflictException('用户不存在');
    const ispassMatch = verify(user.password, password);
    if (!ispassMatch) throw new UnauthorizedException('无效凭据 401');

    console.log(user, '21312')

    return {
      id: user.id,
      name: user.name,
    };
  }

  async login(userId: number, name: string) {
    const { accessToken,refreshToken } = await this.generateTokens(userId);
    return {
      id:userId,
      name:name,
      accessToken,
      refreshToken
    }
  }

  async generateTokens(userId: number) {
    const payload: JwtPayload = { sub: userId };
    const [accessToken, refreshToken] = await Promise.all([
      this.jwtService.signAsync(payload),
      this.jwtService.signAsync(payload, this.refreshTokenConfig),
    ]);
    return {
      accessToken,
      refreshToken,
    };
  }


  async valiadateJwtUser(userId:number){
    const user = await this.userService.findById(userId);
    if(!user){
      throw new UnauthorizedException('401 无效的用户')
    }
    const currentUser = {id: user.id}
    return currentUser
  }

  async valiadateRefreshToken(userId:number){
     const user = await this.userService.findById(userId);
     if(!user){
      throw new UnauthorizedException('401 无效的用户')
     }
     const currentUser = {id: user.id}
     return currentUser
  }

  async refreshToken(userId:number,name:string){
    const { accessToken,refreshToken } = await this.generateTokens(userId);
    return {
      id:userId,
      name:name,
      accessToken,
      refreshToken
    }
  }
}


